package com.ordertracker.endpoint;

import com.ordertracker.Application;
import com.ordertracker.persistent.dictionary.Organization;
import com.ordertracker.protocol.CommandMessage;
import com.ordertracker.security.ApplicationSecurityContext;
import com.ordertracker.service.ActionType;
import com.ordertracker.service.HandleChain;
import com.sun.jersey.spi.container.ContainerRequest;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.io.Serializable;

/**
 * Description of class.
 * Created 1/9/13 7:23 PM
 *
 * @author andrey.rodin@playtech.com
 */

@Component
@Path("/dictionaries")
public class DictionaryEndPoint<T extends Serializable> {

    private static Logger logger = Logger.getLogger(DictionaryEndPoint.class);

    private String entity;

    public DictionaryEndPoint(@PathParam("/{entityName}") String entity) {
        this.entity = entity;
    }

    public DictionaryEndPoint() {
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/{entityName}/{actionName}")
    public Response handleMessage(@Context Request request, @PathParam("entityName") String entityName, @PathParam("actionName") String actionName, CommandMessage msg) {
        System.out.println(entityName + " "+ actionName);
        logger.debug("Handle: service name= " + entityName + " action name= " + actionName);
        logger.debug("Message: "+msg.getObj());
        HandleChain bean = (HandleChain)Application.getApplication().getConfig().getContext().getBean(entityName);
        ApplicationSecurityContext securityContext = (ApplicationSecurityContext)(((ContainerRequest) request).getSecurityContext()) ;
        Response response = null;
        try{
            response = bean.handleMessage(securityContext.getSession(), msg, ActionType.byName(actionName));
        } catch (WebApplicationException we) {
            Response.status(we.getResponse().getStatus()).build();
        } catch (Exception ex) {
            Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }

        return response;
    }

    @GET
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/{entityName}/{actionName}/{id}")
    public Response getHandleMessage(@Context Request request, @PathParam("entityName") String entityName, @PathParam("actionName") String actionName, @PathParam("id") Long id) {
        HandleChain bean = (HandleChain)Application.getApplication().getConfig().getContext().getBean(entityName);
        ApplicationSecurityContext securityContext = (ApplicationSecurityContext)(((ContainerRequest) request).getSecurityContext()) ;
        Response response = null;
        try{
            response = bean.handleMessage(securityContext.getSession(), new CommandMessage(String.valueOf(id), bean.getClass()), ActionType.byName(actionName));
        } catch (WebApplicationException we) {
            Response.status(we.getResponse().getStatus()).build();
        } catch (Exception ex) {
            Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }

        return response;

    }

    @GET
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/{entityName}/{actionName}/field={param}/value={val}")
    //TODO: Need to use getByCriteria
    public Response getByCriteria(@Context Request request, @PathParam("entityName") String entityName,
                                  @PathParam("actionName") String actionName, @PathParam("param") String param, @PathParam("val") String val) {
        HandleChain bean = (HandleChain)Application.getApplication().getConfig().getContext().getBean(entityName);

        ApplicationSecurityContext securityContext = (ApplicationSecurityContext)(((ContainerRequest) request).getSecurityContext()) ;
        Response response = null;
        try{
            response = bean.handleMessage(securityContext.getSession(), new CommandMessage(param + "," + val, bean.getClass()), ActionType.byName(actionName));
        } catch (WebApplicationException we) {
            Response.status(we.getResponse().getStatus()).build();
        } catch (Exception ex) {
            Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }

        return response;

    }


    @GET
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/{entityName}/list/from={id}limit={count}")
    public Response getListHandleMessage(@Context Request request, @PathParam("entityName") String entityName, @PathParam("actionName") String actionName, @PathParam("id") Long id) {
        HandleChain bean = (HandleChain)Application.getApplication().getConfig().getContext().getBean(entityName);
        ApplicationSecurityContext securityContext = (ApplicationSecurityContext)(((ContainerRequest) request).getSecurityContext()) ;
        Response response = null;
        try{
            response = bean.handleMessage(securityContext.getSession(), new CommandMessage(String.valueOf(id), Organization.class), ActionType.byName(actionName));
        } catch (WebApplicationException we) {
            Response.status(we.getResponse().getStatus()).build();
        } catch (Exception ex) {
            Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }

        return response;

    }
}
